//
//  CalendarView.m
//  Learn
//
//  Created by apple on 2024/4/6.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "CalendarView.h"
@interface CalendarCell : UICollectionViewCell
/* <#描述#> */
@property (nonatomic, strong) UILabel    * dayLabel;

@end

@implementation CalendarCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initUI];
    }
    return self;
}
- (void)initUI {
    [self.contentView addSubview:self.dayLabel];
}
- (UILabel *)dayLabel {
    if(!_dayLabel){
        _dayLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 32, 32)];
        _dayLabel.center = self.contentView.center;
        _dayLabel.backgroundColor = UIColor.whiteColor;
        _dayLabel.text = @"";
        _dayLabel.textColor = [UIColor blackColor];
        _dayLabel.font = PingFangMediumFont(14);
        _dayLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _dayLabel;
}

@end

@interface CalendarView ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    //星期
    UIView * _headView;

    CalendarModel * _selectModel;
    
    NSCalendar  * calendar;
    NSDate      * currentDate;// 当期日期
    NSInteger     selectedIndex;
}
@property (nonatomic, strong) UICollectionView    * myCollectionView;
@property (nonatomic, strong) NSMutableArray    * dataArray;

@end

@implementation CalendarView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self createUI];
    }
    return self;
}
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (void)createUI {
    calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];// 指定日历的算法
    currentDate = [NSDate date];
    selectedIndex = [self getTheDateInCalendarTodaySubscript];
    [self addSubview:self.myCollectionView];
}

- (UICollectionView *)myCollectionView {
    if (!_myCollectionView) {
        UICollectionViewFlowLayout *myCollectionLayout = [[UICollectionViewFlowLayout alloc]init];
        myCollectionLayout.minimumInteritemSpacing = 0.5;
        myCollectionLayout.minimumLineSpacing = 0.5;
        myCollectionLayout.itemSize = CGSizeMake((self.width-3)/7.0f,(self.width-3)/7.0f);
        
        _myCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.width, self.height) collectionViewLayout:myCollectionLayout];
        _myCollectionView.delegate = self;
        _myCollectionView.dataSource = self;
        
        _myCollectionView.backgroundColor = UIColor.whiteColor;
        [_myCollectionView registerClass:CalendarCell.class forCellWithReuseIdentifier:@"CalendarCell"];
        [_myCollectionView registerClass:UICollectionViewCell.class forCellWithReuseIdentifier:@"UICollectionViewCell"];

        
        //        [FWMJRefreshManager refresh:_myCollectionView target:self headerRereshAction:@selector(refreshHeader) footerRereshAction:@selector(refreshFooter)];
    }
    return _myCollectionView;
}


#pragma mark collectionView delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSDate * amonthOf1_Date = [self getAMonthframDate:currentDate months:0];
//   目标月的天数+星期数（这天星期几就加几）---目的->布局cell时候能够让每个月1号对应上星期数
    NSInteger days = [self getCurrentMonthForDays];
    NSInteger week = [self getFirstDayWeekForMonth:amonthOf1_Date];
    return days + week;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CalendarCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CalendarCell" forIndexPath:indexPath];
    NSDate * amountOf1_Date =[self getAMonthframDate:currentDate months:0];
    NSInteger number;
    number = [self getFirstDayWeekForMonth:amountOf1_Date];

    if (indexPath.item < number) {
        UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
        return cell;
    }else {
        /*******/
        /*
         *  getFirstDayWeekForMonth ->获取目标月份1号是周几
         *  [self getAMonthframDate:currentDate months:0] ->根据当前日期返回目标月1号的date对象(用来计算1号周几)
         *  case1,2,3,4 同理!
        *******/
        // 给item赋值indexPath.item - 第一天是周几 就可以知道这个月日期怎么赋值了
        NSString * calenderStr;
        // 方法定义如果是星期天返回0(为了日历布局) 所以这里处理一下
        if (number == 0){
            calenderStr = [NSString stringWithFormat:@"%ld",(indexPath.item+1)];
        }else{
         calenderStr = [NSString stringWithFormat:@"%ld",(indexPath.item)];
        }
        cell.dayLabel.text = calenderStr;
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
}




// 返回今天日期在日历UI中的位置下标
-(NSInteger)getTheDateInCalendarTodaySubscript
{
    NSDate * amountOf1_Date =[self getAMonthframDate:currentDate months:0];
    NSCalendarUnit dayInfoUnits  = NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *components = [calendar components:dayInfoUnits fromDate:currentDate];
    NSLog(@"当前日期的comps=%@ ---- %ld",components,(long)[self getFirstDayWeekForMonth:amountOf1_Date]);
    // 为了对应星期数，前边加了站位cell。所以这里真正下标应该加上星期数(-1不用说了下标从0开始)
    return components.day-1+ [self getFirstDayWeekForMonth:amountOf1_Date];
}

/*
 * 日期转字符串
 * date : 需要转换的日期
 */
-(NSString * )theTargetDateConversionStr:(NSDate * )date
{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//设定时间格式,这里可以设置成自己需要的格式
    NSString *currentDateStr = [dateFormat stringFromDate:date];
    // 根据自己需求处理字符串
    return [currentDateStr substringToIndex:7];
}
// 字符串转date
-(NSDate* )theTargetStringConversionDate:(NSString *)str
{
    //设置转换格式
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //NSString转NSDate
    NSDate *date=[formatter dateFromString:str];
    return date;
}
/*
 *  获取当前月天数
 */
-(NSInteger)getCurrentMonthForDays
{
    NSCalendar *currentCalendar = [NSCalendar currentCalendar];
    NSRange range = [currentCalendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[NSDate date]];
    NSUInteger numberOfDaysInMonth = range.length;
    NSLog(@"nsrange = %@----- %ld",NSStringFromRange(range),range.location);
    return numberOfDaysInMonth;
}
/*
 *  date :当前时间
 *  number:当前月之后几个个月的1号date
 */
-(NSDate *)getAMonthframDate:(NSDate*)date months:(NSInteger)number{

    NSCalendarUnit _dayInfoUnits  = NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *components = [calendar components:_dayInfoUnits fromDate:date];
    components.day = 1;
    if (number!=0) {
      components.month += number;
    }
    NSDate * nextMonthDate =[calendar dateFromComponents:components];
    NSLog(@"nextMonthDate = %@",nextMonthDate);
    return nextMonthDate;
}
/*
 * 获取某个月一共多少天
 * date 要获取的月份的date
 */
-(NSInteger)getNextNMonthForDays:(NSDate * )date
{
    NSInteger monthNum =[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date].length;
//     = (NSInteger)[date YHBaseNumberOfDaysInCurrentMonth];
    return monthNum;
}
/**
 *  获取某个月的1号是星期几
 *  date 目标月的date
 **/
-(NSInteger)getFirstDayWeekForMonth:(NSDate*)date
{
#warning mark -- 有待优化，不知道为什么星期数总是比真实多一天（暂时用➖一天处理了）
//    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; // 指定日历的算法 NSCalendarIdentifierGregorian,NSGregorianCalendar
    // NSDateComponent 可以获得日期的详细信息，即日期的组成
    NSDateComponents *comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekday fromDate:date];
    NSLog(@"comps是这个样子的:%@",comps);
    NSInteger weekday = [comps weekday];
    weekday--;
    NSLog(@"[comps weekday] = %ld",(long)weekday);
    if (weekday == 7) {
        return 0;
    }else return weekday;
}
@end
